﻿#include"Dlist.h"
//申请空间
DLTNode* DLTByNode(DLTDataType x)
{
	DLTNode* node = (DLTNode*)malloc(sizeof(DLTNode));
	if (node == NULL)
	{
		perror("malloc error");
		return NULL;
	}
	node->data = x;
	node->prev = node->next = node;

	return node;
}
//初始化
void DLTInit(DLTNode** pphead)
{
	//给双向链表创建一个哨兵位
	*pphead = DLTByNode(-1);
}
//打印双向链表
void DLTPrintf(DLTNode* phead)
{
	DLTNode* pcur = phead->next;
	printf("head");
	printf("<->");
	while (pcur != phead)
	{
		printf("%d", pcur->data);
		printf("<->");
		pcur = pcur->next;
	}
	printf("head\n" );
}
//尾插
void DLTPushBack(DLTNode* phead, DLTDataType x)
{
	assert(phead);
	DLTNode* newnode = DLTByNode(x);
	//phead  phead->prev newnode
	phead->prev->next = newnode;
	newnode->prev = phead->next;

	phead->prev = newnode;
	newnode->next = phead;
	//newnode->prev = phead->prev;
	//newnode->next = phead;

	//phead->prev->next = newnode;
	//phead->prev = newnode;

}
//头插
void DLTPushFront(DLTNode* phead, DLTDataType x)
{
	assert(phead);
	DLTNode* newnode = DLTByNode(x);
	phead->next->prev = newnode;
	newnode->next = phead->next;

	phead->next = newnode;
	newnode->prev = phead;
}
//尾删
void DLTPopBack(DLTNode* phead)
{
	assert(phead&&phead->prev != phead);
	DLTNode* del = phead->prev;
	del->prev->next = phead;
	phead->prev = del->prev;

	//删除尾
	free(del);
	del = NULL;
}
//头删
void DLTPopFront(DLTNode* phead)
{
	assert(phead && phead->next != phead);
	DLTNode* del = phead->next;
	//phead del del->next
	del->next->prev = phead;
	phead->next = del->next;

	free(del);
	del = NULL;
}
//查找特定数据
DLTNode* DLTFind(DLTNode* phead, DLTDataType x) 
{
	assert(phead);
	DLTNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data = x) 
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
//在pos位置之后插⼊数据
void DLTInsert(DLTNode* pos, DLTDataType x)
{
	//pos newnode pos->next
	assert(pos);

	DLTNode* newnode = DLTByNode(x);
	pos->next->prev = newnode;
	newnode->next = pos->next;

	pos->next = newnode;
	newnode->prev = pos;
}
//删除pos的数据
void DLTErase(DLTNode* pos)
{
	assert(pos);
	//pos->prev pos pos->next
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;

	free(pos);
	pos = NULL;
}